package com.tanyin.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.UUID;

/**
 * JWT工具
 *
 * @author xdf
 */
public class JwtUtil {
    /**
     * 作为redis中key的前缀
     */
    private static final String TOKEN_PREFIX = "Token_";

    /**
     * token过期时间，设置为1天（86400000ms）
     */
    private static final Long EXPIRE_TIME = 86400000L;

    public static String create(Long userId,String username,Integer role) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String key = TOKEN_PREFIX + "U" + username;
        Algorithm algorithm = Algorithm.HMAC256(key);
        // 附带username信息
        return JWT.create()
                .withClaim("key", key)
                .withClaim("uid", username)
                .withClaim("id","User_"+userId)
                .withClaim("role","Role_"+role)
                .withClaim("uuid", UUID.randomUUID().toString())
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static String create(Long userId,String username) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String key = TOKEN_PREFIX + "U" + username;
        Algorithm algorithm = Algorithm.HMAC256(key);
        // 附带用户信息
        return JWT.create()
                .withClaim("key", key)
                .withClaim("uid", username)
                .withClaim("id","User_"+userId)
                .withClaim("uuid", UUID.randomUUID().toString())
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static String getUser(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("uid").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

}
